<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function db_table($talbe_name)
{
    $CI =& get_instance();
// 	$this->db->dbprefix($talbe_name);
    return $CI->db->protect_identifiers($talbe_name, TRUE);//通过将第二个参数设置为TRUE (boolen) 启用前缀
}

function get_cfg($cfg_name)
{
    $CI   =& get_instance();
    $_CFG = $CI->config->item($cfg_name);
    return $_CFG;
}

//当前时间戳 (日) 算出 这个时间戳的当天最后一秒钟
function ut_form_time($stime)
{
    $dates = date("Y-m-d", $stime);
    $dates = strtotime($dates . " 23:59:59");
    return $dates;
}

/**
 * @access  public
 * @param
 * @return  void
 */
function make_json_result($content, $message = '', $append = array(), $run_die = TRUE, $logging = FALSE)
{
    if ($logging) {
        logging_response('error', "[Debug-Request] $message");
        logging_response('error', "[Debug-Response] " . json_encode($content), $is_response = TRUE);
    }
    make_json_response($content, 0, $message, $append);
}

/**
 * 创建一个JSON格式的错误信息
 * @access  public
 * @param   string $msg
 * @return  void
 */
function make_json_error($message, $append = array(), $run_die = TRUE)
{
    logging_response('error', "$message");
    make_json_response('', 1, $message, $append, $run_die);
}

/**
 * 记录日志
 * @param unknown $level
 * @param unknown $message
 * @param string $is_response
 */
function logging_response($level, $message, $is_response = FALSE)
{
    $CI         =& get_instance();
    $zh_message = iconv("utf-8", "GB2312", $message);

    $CI->load->library('user_agent');
    $agent_string = iconv("utf-8", "GB2312", $CI->agent->agent_string());


    if ($is_response) {
        $log_msg = sprintf('%s', $zh_message);
    } else {
        $request = json_encode($_REQUEST);
        $log_msg = sprintf('%s [IP:%s]->%s?%s <%s>', $zh_message, $CI->input->ip_address(), $CI->router->uri->uri_string, $request, $agent_string);
    }

    log_message($level, $log_msg);
}

/**
 * 创建一个JSON格式的数据
 *
 * @access  public
 * @param   string $content
 * @param   integer $error
 * @param   string $message
 * @param   array $append
 * @return  void
 */
function make_json_response($content = '', $error = "0", $message = '', $append = array(), $run_die = TRUE)
{
    $res = array('error' => $error, 'message' => $message, 'content' => $content);
    if (!empty($append)) {
        foreach ($append AS $key => $val) {
            $res[$key] = $val;
        }
    }
    if ($run_die) {
        die(json_encode($res));
    } else {
        echo json_encode($res);
    }
}

/**
 * 格式化价格
 *
 * @access  public
 * @param   float $price 价格
 * @return  string
 */
function price_format($price, $format = 1, $change_price = true, $currency = '￥')
{
    if ($price === '') {
        $price = 0;
    }
    if ($change_price) {
        $thousands_separator = ',';
        switch ($format) {
            case 0:
                $price = number_format($price, 2, '.', $thousands_separator);
                break;
            case 1: // 保留不为 0 的尾数
                $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', $thousands_separator));

                if (substr($price, -1) == '.') {
                    $price = substr($price, 0, -1);
                }
                break;
            case 2: // 不四舍五入，保留1位
                $price = substr(number_format($price, 2, '.', $thousands_separator), 0, -1);
                break;
            case 3: // 直接取整
                $price = intval($price);
                break;
            case 4: // 四舍五入，保留 1 位
                $price = number_format($price, 1, '.', $thousands_separator);
                break;
            case 5: // 先四舍五入，不保留小数
                $price = round($price);
                break;
        }
    } else {
        $price = number_format($price, 2, '.', ',');
    }

    return sprintf("$currency%s", $price);
}

/**
 * 获取字符串长度的函数
 *
 * @param   string $str 被截取的字符串
 *
 * @return  string
 */
function str_len($str)
{
    preg_match_all('/./us', $str, $match);
    return count($match[0]);  // 输出
}

/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string $str 被截取的字符串
 * @param   int $length 截取的长度
 * @param   bool $append 是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true)
{
    $CI      =& get_instance();
    $charset = $CI->config->item('charset');

    $str       = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength) {
        return $str;
    } elseif ($length < 0) {
        $length = $strlength + $length;
        if ($length < 0) {
            $length = $strlength;
        }
    }
    if (function_exists('mb_substr')) {
        $newstr = mb_substr($str, 0, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        $newstr = iconv_substr($str, 0, $length, $charset);
    } else {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }

    if ($append && $str != $newstr) {
        $newstr .= '...';
    }

    return $newstr;
}

/**
 * 将GMT时间戳格式化为用户自定义时区日期
 *
 * @param  string $format
 * @param  integer $time 该参数必须是一个GMT的时间戳
 *
 * @return  string
 */
function time_format($time = NULL, $format = NULL)
{
    $format = $format == NULL ? get_cfg('time_format') : $format;
    return local_date($format, $time = NULL);
}

function local_date($format, $time = NULL)
{
    $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : 8;

    if ($time === NULL) {
        $time = gmtime();
    } else if ($time <= 0) {
        return '';
    }
    $time += ($timezone * 3600);

    return date($format, $time);
}

/**
 * 获得当前时区的时间戳
 *
 * @return  integer
 */
function local_time()
{
    return strtotime(local_date("Y-m-d H:i:s", gmtime()));
}

/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
    return (time() - date('Z'));
}

/**
 * 生成随机的字符串(已去除0 o O )
 *    $length 长度
 *    $type 类型：all;(num lower upper可以组合)
 * @return string
 */
function random_str($length, $type = 'all')
{
    $nums   = '123456789';
    $lowers = 'abcdefghijklmnpqrstuvwxyz';
    $uppers = 'ABCDEFGHIJKLMNPQRSTUVWXYZ';
    if ($type == 'all') {
        //$src = preg_replace("/[0o1iI]/", "", $nums . $lowers . $uppers);
        $chars = $nums . $lowers . $uppers;
    } else {
        $chars = '';
        if (strpos($type, 'num') !== false)
            $chars .= $nums;
        if (strpos($type, 'lower') !== false)
            $chars .= $lowers;
        if (strpos($type, 'upper') !== false)
            $chars .= $uppers;
    }
    if ($chars) {
        for ($i = 0, $count = strlen($chars); $i < $count; $i++) {
            $arr[$i] = $chars[$i];
        }
        mt_srand((double)microtime() * 1000000);
        shuffle($arr);
        $randoms = substr(implode('', $arr), 0, $length);
    } else {
        $randoms = $chars;
    }
    return $randoms;
    //return $chars ? substr(str_shuffle($chars), 0, $length) : $chars;
}

function is_mobile($mobile)
{
    if (!empty($mobile)) {
        return preg_match("/^1[34578][0-9]{9}$|^861[34578][0-9]{9}$/", $mobile);
    } else {
        return FALSE;
    }
}


/**
 * 根据用户IP地址定位用户城市
 *
 * @access  public
 * @return  array
 */
function get_ip_region($ip_address = '')
{
    if (empty($ip_address)) {
        $CI         =& get_instance();
        $ip_address = $CI->input->ip_address();
    }
// 		$api_url = "http://ip.taobao.com/service/getIpInfo.php?qq-pf-to=pcqq.c2c&ip=%s";
// 		$taobao_string = file_get_contents(sprintf($api_url, $user_ip));
// 		$decode_taobao = json_decode($taobao_string, true);
// 		print_r($decode_taobao);

    $api_url     = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=%s";
    $sina_string = file_get_contents(sprintf($api_url, $ip_address));
    $sina_string = ltrim(rtrim($sina_string, ";"), "var remote_ip_info = ");

//	Array ( [ret] => 1 [start] => 180.152.0.0 [end] => 180.175.255.255 [country] => 中国 [province] => 上海 [city] => 上海 [district] => [isp] => 电信 [type] => [desc] => ) 
// 	Array ( [ret] => -1 [ip] => 127.0.0.1 )
    $ip_info = json_decode($sina_string, true);
    if ($ip_info['ret'] <= 0) {
        $ip_info = Array('country' => '中国', 'province' => '上海', 'city' => '上海');
    }
    return $ip_info;
}

/**
 * 根据经纬度获取高德地图位置信息,返回格式化地图数据
 * @param string $longitude 经度
 * @param string $latitude 纬度
 * @param bool $pois 是否获取周边兴趣点
 * @param number $radius 定义周边信息的半径，单位米
 * @param API地址
 * SELECT lng,lat,
 * (POWER(MOD(ABS(lng - $lng),360),2) + POWER(ABS(lat - $lat),2)) AS distance
 * FROM `user_location`
 * ORDER BY distance LIMIT 100
 * http://restapi.amap.com/v3/geocode/regeo?location=121.468674,31.271999&key=ac9a29dd78fc7192a4160d255b7b16cb&s=rsv3&radius=1000&extensions=all
 * @return string-json
 * {"status":"1","info":"OK", "regeocode":{
 *        "formatted_address":"上海市虹口区广中路街道柳林公寓",
 *        "addressComponent":{"province":"上海市","city":[],"citycode":"021","district":"虹口区","adcode":"310109","township":"广中路街道",
 *        "neighborhood":{"name":"柳林公寓","type":"商务住宅;住宅区;住宅小区"},"building":{"name":[],"type":[]},
 *        "streetNumber":{"street":"柳营路","number":"65","location":"121.469311,31.271745","direction":"东","distance":"66.8214"},
 *        "businessAreas":[{"location":"121.46950559316242,31.278132570940173","name":"广中路","id":"310109"}]
 *        }
 * }} *
 * @param unknown $location
 * @return multitype:unknown
 */
function amap_location_data($location)
{
    $Longitude = $location['Longitude'];
    $Latitude  = $location['Latitude'];
    if (is_array($Longitude)) {
        $Longitude = $Longitude[0];
    }
    if (is_array($Latitude)) {
        $Latitude = $Latitude[0];
    }
    //根据经纬度换取地址信息
    $mapApi_url = "http://restapi.amap.com/v3/geocode/regeo?key=ac9a29dd78fc7192a4160d255b7b16cb&s=rsv3";
    $mapApi_url .= "&location=" . $Longitude . "," . $Latitude;
    $mapApi_url .= "&radius=1000&extensions=all";

    $amap_str = file_get_contents($mapApi_url);
    $amap     = json_decode($amap_str);

    $result['address']  = $amap->regeocode->formatted_address;
    $result['province'] = $amap->regeocode->addressComponent->province;
    $city               = $amap->regeocode->addressComponent->city;
    $result['city']     = empty($city) ? $result['province'] : $city;
    $result['raw_data'] = $amap_str;//原始数据
    return $result;
}

/**
 * 获取email的访问地址
 * @param string $email
 * @return Ambigous <string>|boolean
 */
function email_in_hosts($email)
{
    $email_arr  = explode('@', $email);
    $mail_hosts = array(
        '126.com'      => 'http://www.126.com',
        '163.com'      => 'http://mail.163.com',
        'tom.com'      => 'http://mail.tom.com',
        'sohu.com'     => 'http://mail.sohu.com',
        'sina.com'     => 'http://mail.sina.com',
        'sina.com.cn'  => 'http://mail.sina.com.cn',
        'aol.com'      => 'http://mail.aol.com',
        'yahoo.com'    => 'http://mail.yahoo.com',
        'yahoo.com.cn' => 'http://mail.yahoo.com.cn',
        '21cn.com'     => 'http://mail.21cn.com',
        'qq.com'       => 'http://mail.qq.com',
        'laohuyou.com' => 'http://exmail.qq.com'
    );
    if (array_key_exists($email_arr[1], $mail_hosts)) {
        return $mail_hosts[$email_arr[1]];
    } else {
        return FALSE;
    }
}

function ur_here()
{
    $CI       =& get_instance();
    $urhere[] = array('title' => '管理中心', 'type' => 'home', 'url' => site_url('./'));
    switch ($CI->router->class) {
        case 'index':
            $urhere[] = array('title' => '首页');
            break;
        case 'tour':
            $urhere[] = array('title' => '线路管理', 'url' => site_url('tour'));
            switch ($CI->router->method) {
                case 'index':
                    $urhere[] = array('title' => '线路列表');
                    break;
                case 'edit':
                    $urhere[] = array('title' => '编辑线路');
                    break;
            }
            break;
    }
    foreach ($urhere as $key => $item) {
        if (!isset($item['type'])) {
            $urhere[$key]['type'] = '';
        }
        if (!isset($item['url'])) {
            $urhere[$key]['url'] = '';
        }
    }
    end($urhere);
    $key = key($urhere);
    if (empty($urhere[$key]['type'])) {
        $urhere[$key]['type'] = 'active';
    }
    return $urhere;
}

/**
 * 格式化价格
 *
 * @access  public
 * @param   float $price 价格
 * @return  string
 */
function mobile_format($mobile, $fill_str = ' ')
{
    return substr($mobile, 0, 3) . $fill_str . substr($mobile, 3, 4) . $fill_str . substr($mobile, -4);
}

/**
 * 用法 echo remote_filesize($url,$user='',$pw='');
 * $url = "http://www.nowamagic.net/librarys/images/random/rand_11.jpg";
 * echo remote_filesize($url,$user='',$pw='');
 *
 */
function remote_filesize($uri, $user = '', $pw = '')
{
    // start output buffering
    ob_start();
    // initialize curl with given uri
    $ch = curl_init($uri); // make sure we get the header
    curl_setopt($ch, CURLOPT_HEADER, 1); // make it a http HEAD request
    curl_setopt($ch, CURLOPT_NOBODY, 1); // if auth is needed, do it here
    if (!empty($user) && !empty($pw)) {
        $headers = array('Authorization: Basic ' . base64_encode($user . ':' . $pw));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $okay = curl_exec($ch);
    curl_close($ch); // get the output buffer
    $head = ob_get_contents(); // clean the output buffer and return to previous // buffer settings
    ob_end_clean();  // gets you the numeric value from the Content-Length // field in the http header
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);  // if there was a Content-Length field, its value // will now be in $matches[1]
    if (isset($matches[1])) {
        $size = $matches[1];
    } else {
        $size = 'unknown';
    }
    $last_mb = round($size / (1024 * 1024), 3);
    $last_kb = round($size / 1024, 3);
    return $last_kb . 'KB / ' . $last_mb . ' MB';
}

function authorize_hash($hash, $start = 7, $len = 24)
{
    return substr(md5($hash . substr(gmtime(), 0, 7)), $start, $len);
}

/**
 * Curl版本
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_curl('http://www.qianyunlai.com/restServer.php', $post_array);
 */
function request_by_curl($remote_server, $post_array = array())
{
    $ch      = curl_init();
    $timeout = 10;
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "IBGMerchant_CURL");
    if (!empty($post_array)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
    }
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}

/**
 * 显示一个提示信息
 *
 * @access  public
 * @param   string $content
 * @param   array $links
 * @param   string $type 信息类型：warning, error, info
 * @param   string $auto_redirect 是否自动跳转
 * @return  void
 */
function show_message($message, $hrefs = array(), $type = 'info', $auto_redirect = true)
{
    $_this =& get_instance();
    $links = array();
    if (empty($hrefs) || !is_array($hrefs)) {
        $links[] = array('text' => "返回上一页", 'href' => 'javascript:history.go(-1)');
    } else {
        if (count($hrefs) == count($hrefs, 1)) {
            $links[] = $hrefs;
        } else {
            $links = $hrefs;
        }
    }
    $this_datas['message']       = $message;
    $this_datas['auto_redirect'] = $auto_redirect;
    $this_datas['msg_type']      = $type;
    $this_datas['default_url']   = $links[0];
    //修正链接地址
    foreach ($links as $key => $val) {
        if (strpos($val['href'], 'http://') === false &&
            strpos($val['href'], 'https://') === false &&
            strpos($val['href'], 'javascript:') === false
        ) {
            $links[$key]['href'] = site_url($val['href']);
        }
    }
    $this_datas['links'] = $links;

    $_this->load->view('message', $this_datas);
    $_this->output->_display();
    exit;
}

function check_float($value, $isPlus = false)
{
    if (is_numeric($value)) {
        if ($isPlus && floatval($value) < 0.0) {
            return false;
        }
        return true;
    } else {
        return false;
    }

}

//推送至nodejs服务器
//$type = 1 推送给所有人 =2 按别名推送 =3 按标签推送
//$obj 一唯数组
//$environment 1推送给用  2推送给小屋人员
//$action_array 自定义参数二维数组
/**
 * @$action_array
 * push_type = 1 刷新的、
 * refresh_code:
 * home 刷新首页
 * myred 刷新红点
 * privilege 特权
 */


function push_jp($type = 1, $environment = 2, $obj, $log_id = 0, $content = '', $action_array = array())
{
    $key_code   = 'abcd-123qwe-147tyu-357';
    $CI         =& get_instance();
    $purl       = $CI->config->item('nodejs_url') . 'push/';
    $post_array = array();
    switch ($type) {
        case 1:
            $purl .= 'push_all';
            $post_array = array('key_code' => $key_code, 'environment' => $environment, 'log_id' => $log_id, 'content' => $content, 'action_array' => $action_array);
            break;
        case 2:
            $purl .= 'push_batch';
            $post_array = array('key_code' => $key_code, 'environment' => $environment, 'log_id' => $log_id, 'content' => $content, 'action_array' => $action_array, 'account_array' => $obj);
            break;
        case 3:
            $purl .= 'push_tags';
            $post_array = array('key_code' => $key_code, 'environment' => $environment, 'log_id' => $log_id, 'content' => $content, 'action_array' => $action_array, 'taglist' => $obj);
            break;
    }
    return this_request_by_curl($purl, $post_array);
}


/**
 * Curl版本 post
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_curl('http://www.qianyunlai.com/restServer.php', $post_array);
 */
function this_request_by_curl($remote_server, $post_array = array())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_array));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "CURL Example beta");
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}


/**
 * $online  1：线上，2：线下
 * $card_type 0：医护，1：后勤，2：实习生
 * @return [type] [description]
 */
function buildCardNumber($enterprise_id, $online, $card_type)
{
    //企业ID
    $enterprise_id = getLeftFillZero($enterprise_id, 6);
    // 卡号类型
    $card_type = getLeftFillZero($card_type, 1);
    //6位流水号
    $timestamp = microtime();
    $arr       = explode(" ", $timestamp);
    $micro     = $arr[0] * 100000000;
    $micro_str = substr($micro . "", 0, 6);
    $number    = str_shuffle($micro_str);
    //随机数
    $str_rand       = rand(0, 9);
    $server_node_id = ini_get('donkeyid.node_id');
    $server_node_id = $server_node_id === false ? rand(10, 99) : $server_node_id;

    return strval($enterprise_id) . $card_type . $online . $server_node_id . $number . $str_rand;
}

/**
 * 左边自动补零
 */
function getLeftFillZero($str, $len)
{
    return str_pad($str, $len, "0", STR_PAD_LEFT);
    // return substr(strval($str+1000), 1, $len);
}

/**
 * 账号生成方法
 * 账号规则：
 *
 *  企业ID（6位数 不足前面用0补充）
 *  6位数 加上 (0-9的随机数)
 *
 *  eg:005482 000001 9
 *
 * @return [type] [description]
 */
function buildAccountNo($enterprise_id)
{
    //企业ID
    $enterprise_id = getLeftFillZero($enterprise_id, 6);
    //6位流水号
    $timestamp = microtime();
    $arr       = explode(" ", $timestamp);
    $micro     = $arr[0] * 100000000;
    $micro_str = substr($micro . "", 0, 6);
    $number    = str_shuffle($micro_str);
    //随机数
    $str_rand = rand(0, 9);

    // 每台服务器nodeid
    $server_node_id = ini_get('donkeyid.node_id');
    $server_node_id = $server_node_id === false ? rand(10, 99) : $server_node_id;

    return strval($enterprise_id) . $server_node_id . $number . $str_rand;
}

/**
 * 卡解密
 * @param $secretdata
 * @return string
 */
function decode($secretdata)
{
    $encrypt_key = 'VZD8PWEDXZ9Z9XVNAPCN9ZU4ZABFCHP5';
    $iv          = '001RG1HNDFIBB4GR';
    $cryptkey    = hash('sha256', $encrypt_key, true);
    return openssl_decrypt($secretdata, 'aes-256-cbc', $cryptkey, false, $iv);
}

/**
 * 通过物理卡号读取卡号
 * @param int $pysicalnum
 * @return string
 */
function getCardNumByPhysicalNum($pysicalnum = 0)
{
    $pysicalnum = sprintf("%06d", $_SESSION['hospital_id']) . intval($pysicalnum);
    $CI         =& get_instance();
    $db         = $CI->load->database('epay', TRUE);     //切换数据库
    $db->select('card_number');
    $db->from('card_number_entity');
    $db->where('enter_physical', $pysicalnum);
    $data = $db->get()->row_array();
    return empty($data['card_number']) ? '' : $data['card_number'];
}

//加密
function encode($secretdata)
{
    $encrypt_key = 'VZD8PWEDXZ9Z9XVNAPCN9ZU4ZABFCHP5';
    $iv          = '001RG1HNDFIBB4GR';
    $cryptkey    = hash('sha256', $encrypt_key, true);
    return openssl_encrypt($secretdata, 'aes-256-cbc', $cryptkey, false, $iv);
}

/**
 * 生成 账单流水号
 * @return [type] [description]
 */
//旧
/*function buildBillNumber($prefix = '')
{
    return $prefix . date('ymdHis') . rand(1000, 2000) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}*/

function buildBillNumber($prefix = '')
{
    return $prefix . date('ymdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 10, 13), 1))), 0, 3) . str_pad(mt_rand(1, 999), 3, 0, STR_PAD_LEFT) . substr(microtime(), 2, 6);
}


/**
 * @param int $formate 输出格式 1 00:00:00 2  00:00
 * @param int $start 开始时间
 * @param int $end 结束时间
 * @return array        返回一维数组
 */
function select_date($formate = 1, $start = 0, $end = 24)
{
    $date = array();
    for ($i = $start; $i <= $end; $i++) {
        $temp = sprintf("%02d", $i);
        if ($formate == 1) {
            $date[] = "{$temp}:00:00";
            if ($temp != 24)
                $date[] = "{$temp}:30:00";
        } elseif ($formate == 2) {
            $date[] = "{$temp}:00";
            if ($temp != 24)
                $date[] = "{$temp}:30";
        }
    }
    return $date;
}

/**
 * $ret 数据源
 * $v页面输出字段
 * $text 字段不存在或为空时 输出的默认值
 * @return  string
 */
function isset_echo($ret, $v = '', $text = '')
{
    echo (isset($ret[$v]) && !empty($ret[$v])) ? $ret[$v] : $text;
}

/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl  = $url;
    $curlPost = $param;
    $ch       = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);

    return $data;
}

/**
 * curl函数
 * @param  [type] $url    [description]
 * @param  [type] $params [description]
 * @param  string $method [description]
 * @return [type]         [description]
 */
function curl_request($url, $params, $method = 'get')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    // curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, '');
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);

    // 处理文件上传
    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
        foreach ($params as $k => &$v) {
            if (preg_match('/^\@(.*\.(jpg|png|mp3|wav|gif|doc|docx|xls|xlsx|ico|zip|rar|csv|pdf))$/', $v, $match)) {
                $filepath = $match[1];
                $v        = new CURLFile($filepath);
            }
        }
    }

    // METHOD
    $method = strtoupper($method);
    switch ($method) {
        case 'POST':
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            break;
        case 'PUT':
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            break;
        case 'PATCH':
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PATCH'));
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            break;
        case 'DELETE':
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
        case 'GET':
            $suffix = http_build_query($params);
            curl_setopt($curl, CURLOPT_URL, $url . ($suffix ? '?' . $suffix : ''));
    }

    $param_string = http_build_query($params);

    $result = curl_exec($curl);

    $response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    return $result;
}


//盐值加密算法
function salt_sign()
{
    $encrypt_str = get_salt_key();
    $day         = date('j');
    //$day = 17;
    $len = strlen($encrypt_str);

    for ($i = 0; $i < $len; $i++) {
        $encrypt_arr[] = ord($encrypt_str{$i});
    }
    $encrypt_arr2 = array();

    for ($i = 0; $i < $len; $i++) {
        if ($i % 2 != 0) {
            $encrypt_arr2[] = $encrypt_arr[$i] - $i * 2 + $day;
        } else {
            $encrypt_arr2[] = $encrypt_arr[$i];
        }
    }

    $t = NULL;
    for ($i = 0; $i < $len; $i++) {
        $t = $encrypt_arr2[$i];
        $t = $t ^ ($i % 3);
        $t = $t >> 3;
        if ($i % 3 == 0) {
            $t = $t << 2;
        } else {
            $t = $t ^ $encrypt_arr2[$i];
        }
        $encrypt_arr3[] = $t;
    }

    $enkey = md5(implode('', $encrypt_arr3));
    return $enkey;
}


//获取client sigin

function checkSign($data, $client_sign)
{
    $salt            = config_item('salt_code');
    $salt_new        = salt_sign();
    $server_sign     = md5($salt . $data . $salt);
    $server_sign_new = md5($salt_new . $data . $salt_new);
    if (empty ($client_sign) || empty($server_sign) || empty($server_sign_new)) {
        $result['msg_code'] = '0011';
        die(returnJson($result));
    }
    if (($client_sign != $server_sign) && ($client_sign != $server_sign_new)) {
        $result['msg_code'] = '0011';
        die(returnJson($result));
    }
    return json_decode($data, true);

}


//获取salt秘钥
function get_salt_key()
{
    $salt_key = 'MmLPCVTQepQPRGME%$sadA#$@!ESAD78';
    return $salt_key;
}


function search_array($obj, $array_data, $cloumn_name = 'id')
{
    if (empty($obj)) {
        return false;
    }

    if (empty($array_data)) {
        return false;
    }

    $result = array();
    foreach ($array_data as $key => $value) {
        if ($value[$cloumn_name] == $obj) {
            array_push($result, $array_data[$key]);
        }
    }
    return $result;
}


/**
 * 短信推送请求体
 * @param  [type] $mobile [description]
 * @param  [type] $msg    [description]
 * @return [type]         [description]
 */
function sendSms($mobile, $msg)
{
    $data             = array();
    $CI               =& get_instance();
    $data['action']   = 'send';
    $data['account']  = $CI->config->item('sms_account');
    $data['password'] = $CI->config->item('sms_password');
    $data['mobile']   = $mobile;
    $data['content']  = $CI->config->item('sms_prefix') . $msg;  //'您好您的验证码是12345';

    $response = request_post($CI->config->item('sms_send_interface'), $data);
    $res      = json_decode($response, true);


    if ($res['returnstatus'] == 'Success' && $res['message'] == '操作成功') {
        $data['action'] = 'query';
        $data['taskid'] = $res['taskID'];
        $response       = request_post($CI->config->item('sms_verify_interface'), $data);
        $res            = json_decode($response, true);
    }
    if (intval($res['error']) == 1) {
        return $res;
    } else {
        return false;
    }
}


/**
 * 生成完整图片 阿里OSS HTTP路径
 * @return  string
 */
function get_image_oss($image, $default_img = 'no_picture')
{
    $_this =& get_instance();
    if (!empty($image)) {
        $re_image = $_this->config->item('imageurl') . $image;
    } else {
        $default_image = full_static_url($_this->config->item($default_img));
        $re_image      = $default_image;
    }
    return $re_image;
}

/**
 * 生成完整图片 阿里OSS CDN HTTP路径
 * @return  string
 */
function get_image_cdn_oss($image, $default_img = 'no_picture')
{
    $_this =& get_instance();
    if (!empty($image)) {
        $re_image = $_this->config->item('cdnimageurl') . $image;
    } else {
        $default_image = full_static_url($_this->config->item($default_img));
        $re_image      = $default_image;
    }
    return $re_image;
}

/**
 * 判断用户权限
 * @param $pri_id
 * @return bool
 */
function check_privilege($pri_id)
{
    //暂时关闭
    //return true;
    $CI =& get_instance();
    /*if (!isset($_SESSION['privilege_ids'])) {
        make_json_error('对不起,您没有执行此项操作的权限!');
        return;
    }*/
    if (!in_array($pri_id, $_SESSION['privilege_ids']) && !$_SESSION['is_web_admin_role']) {
        if ($CI->input->is_ajax_request()) {
            make_json_error('对不起,您没有执行此项操作的权限!');
        } else {
            $links = array();
            show_message('没有权限操作!', $links, 'error');
        }
    }
}

function check_privilege_view($pri_id)
{
    // 暂时关闭
    //return true;
    /*if (!isset($_SESSION['privilege_ids'])) {
        return false;
    }*/
    if (!in_array($pri_id, $_SESSION['privilege_ids']) && !$_SESSION['is_web_admin_role']) {
        return false;
    } else {
        return true;
    }
}